package com.sy.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.sy.bean.Goods;
import com.sy.bean.GoodsList;
import com.sy.bean.pucharse.excel.GoodsExcel;
import com.sy.bean.pucharse.excel.GoodsImportExcel;
import com.sy.bean.pucharse.excel.PurchaseExcel;
import com.sy.bean.report.PurchaseReportExcel;
import com.sy.common.crud.BaseServiceImpl;
import com.sy.common.crud.IService;
import com.sy.common.exception.BusinessException;
import com.sy.common.utils.UploadUtils;
import com.sy.mapper.GoodsListConditionMapper;
import com.sy.mapper.GoodsMapper;
import com.sy.service.GoodsListConditionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.prefs.BackingStoreException;

@Service
public class GoodsListConditionServiceImpl extends BaseServiceImpl<GoodsList, GoodsListConditionMapper> implements GoodsListConditionService {

    @Autowired
    GoodsListConditionMapper goodsListConditionMapper;

    @Autowired
    HttpServletRequest request;


    @Override
    public String goodsExport(Map map) {
        List<GoodsExcel> list = goodsListConditionMapper.goodsExport(map);
        String root = request.getServletContext().getRealPath("/")+"/excel";
        File file = new File(root);
        if (!file.exists())
            file.mkdirs();
        String newFileName = file.getAbsolutePath() + "/商品列表.xlsx";
        EasyExcel.write(newFileName, GoodsExcel.class)
                .sheet("采购报表列表")
                .doWrite(() -> {
                    return list;
                });
        return "/excel/商品列表.xlsx";
    }

    int rs;
    @Override
    public int readExcel(MultipartFile file) {
        rs=-1;
        //先将excel上传到服务器
        UploadUtils utils = new UploadUtils();
        String path = utils.toUpload(file,request,"excel");
        //获取服务器根目录
        String root = request.getServletContext().getRealPath("/");
        String fileName = root + path;

        EasyExcel.read(fileName, GoodsImportExcel.class,new PageReadListener<GoodsImportExcel>(datalist->{
            //批量插入
            rs = baseMapper.batchImport(datalist);
        })).sheet().doRead();
        return rs;
    }


}
